package com.mktneutral.dividends.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class DividendsFrontend implements EntryPoint {
	/**
	 * URL for the JSON records data.
	 */
	private static final String RECORDS_JSON_URL = "records.json";
	
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		final RootPanel dataTable = RootPanel.get("dataTableTbody");
		final RootPanel previous30Td = RootPanel.get("prev30Td");
		final RootPanel next30Td = RootPanel.get("next30Td");
		
		next30Td.sinkEvents(Event.ONCLICK);
		next30Td.addHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Window.alert("YOU CLICKED THE NEXT 30 TD");
			}
		}, ClickEvent.getType());
		
		previous30Td.sinkEvents(Event.ONCLICK);
		previous30Td.addHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				Window.alert("YOU CLICKED THE PREVIOUS 30 TD");
			}
		}, ClickEvent.getType());
		
		RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, RECORDS_JSON_URL);
		try {
			requestBuilder.sendRequest(null, new RequestCallback() {
				public void onError(Request request, Throwable throwable) {
					Window.alert("Failed to load the request");
				}
			
				public void onResponseReceived(Request request, Response response) {
					JSONObject records = (JSONObject) JSONParser.parse( response.getText() );
					JSONArray recordsArray = (JSONArray) records.get("recs");
					
					for ( int i=0; i<recordsArray.size(); i++ ) {
				        Element tr = getTableRow((JSONObject) recordsArray.get(i), i);
						dataTable.getElement().appendChild( tr );
					}
				}
			});
		} catch ( RequestException re ) {
			Window.alert("AJAX request failed.");
		}
	}
	
	public Element getTableRow(JSONObject record, int idx) {
		Element tickerTd = DOM.createTD();
		tickerTd.setInnerText( record.get("t").isString().stringValue() );
		
		Element nameTd = DOM.createTD();
		if ( record.get("n") != null ) { 
			nameTd.setInnerText( record.get("n").isString().stringValue() );
		}
		
		Element industryTd = DOM.createTD();
		industryTd.setInnerText( record.get("i").isString().stringValue() );
		Element sectorTd = DOM.createTD();
		sectorTd.setInnerText( record.get("s").isString().stringValue() );
		
		Element marketCapTd = DOM.createTD();
		if ( record.get("mc") != null ) {
			marketCapTd.setInnerText( record.get("mc").isString().stringValue() );
		}
		
		Element yieldTd = DOM.createTD();
		yieldTd.setInnerText( record.get("y").isString().stringValue() );
		
		Element tr = DOM.createTR();
		if ( idx%2 == 0 ) {
			tr.setClassName("white-row");
		} else {
			tr.setClassName("blue-row");
		}
		
		tr.appendChild( tickerTd );
		tr.appendChild( nameTd );
		tr.appendChild( industryTd );
		tr.appendChild( sectorTd );
		tr.appendChild( marketCapTd );
		tr.appendChild( yieldTd );
		
		return tr;
	}
	
	public final native void consoleLog(String message) /*-{
		console.log(message);
	}-*/;
}
